﻿
using System;

using GECS.Core;

using NAudio;
using NAudio.Wave;

namespace GECS.Audio
{
	/// <summary>
	/// Represents a Sound. Supports MP3, WAV and AIFF audio. MIDI isn't supported.
	/// </summary>
	class WavSound : Sound
	{
		
		private WaveOut device;
		private WaveStream source;
		
		public WavSound(string name, string extension)
		{
			device = new WaveOut();
			switch (extension.ToLower())
			{
				case ".wav":
					source = new WaveFileReader(Game.GetResourceStream(name));
					break;
				case ".aiff":
					source = new AiffFileReader(Game.GetResourceStream(name));
					break;
				case ".mp3":
					source = new Mp3FileReader(Game.GetResourceStream(name));
					break;
			}
			device.Init(source);
			
			device.PlaybackStopped += delegate(object sender, StoppedEventArgs e) {
				
				IsPlaying = false;
				
				if (Loop)
				{
					// start again
					Play();
				}
				
			};
		}
		
		public override void Play()
		{
			source.CurrentTime = TimeSpan.Zero;
			device.Init(source);
			device.Play();
			IsPlaying = true;
		}
		
		public override void Stop()
		{
			bool loop = Loop;
			if (Loop)
				Loop = false;
			device.Pause();
			IsPlaying = false;
			Loop = loop;
		}
		
		public static bool IsSupported(string extension)
		{
			switch (extension.ToLower())
			{
				case ".mp3":
				case ".wav":
				case ".aiff":
					return true;
			}
			return false;
		}
		
	}
}
